package com.jinniulive.platform.module.live;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.jinniulive.platform.MyApp;
import com.jinniulive.platform.R;
import com.jinniulive.platform.adapter.GiftBaseAdapter;
import com.jinniulive.platform.adapter.LiveActivityViewPager;
import com.jinniulive.platform.bean.HtmlMsg;
import com.jinniulive.platform.bean.UserManageInfo;
import com.jinniulive.platform.module.live.fragments.FaceFragment;
import com.jinniulive.platform.module.live.fragments.GiftFragment;
import com.jinniulive.platform.module.live.fragments.PrivateChatFragment;
import com.jinniulive.platform.module.live.fragments.PublicChatFragment;
import com.jinniulive.platform.module.live.fragments.TeaCherFragment;
import com.jinniulive.platform.module.live.fragments.ThemeFragment;
import com.jinniulive.platform.tools.SocketUtil;
import com.jinniulive.platform.tools.UsersManage;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.widget.media.IjkVideoView;

public class LiveActivity extends AppCompatActivity implements View.OnTouchListener, IMediaPlayer.OnPreparedListener, View.OnClickListener, AdapterView.OnItemSelectedListener, TextView.OnEditorActionListener {

    private IjkVideoView mIjkVideoView;
    private RelativeLayout mLayoutTitle1,mLayoutTitle2,mRelativeLayoutIjk;
    private int mHeightPixels;
    private int mWidthPixels;
    private AudioManager audio;
    private ViewPager mViewPagerShow;
    private TabLayout mTabLayoutShow;
    private LiveActivityViewPager mPagerAdapterShow;
    private List<Fragment> mFragments;
    private FragmentManager mManager;
    private FrameLayout mFrameLayoutFace;
    private Button mButtonback;
    private Boolean is=true;
    private int volume;
    private FaceFragment mFaceFragment;
    private GiftFragment mGiftFragment;
    private SocketUtil mSocketUtil;
    private TextView mTextViewName;
    private Spinner mSpinnerUser;
    private ArrayAdapter<String> mAdapterSpinner;
    private GiftBaseAdapter mSpinnerAdapter;
    private List<String> mListUserName=new ArrayList<>();
    private ImageView mImageViewAnimat;
    private AnimationDrawable animationDrawable;
    private EditText mEditTextSend;
    private int typeChat;
    private MyApp myApp;
    private int userID;
    private int receiverId=0;
    private List<Integer> mUserList=new ArrayList<>();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live);
        initView();
        initData();
        setData();
        setListener();

    }

    //显示Html消息
    public void showHtml(String html,int type){

        HtmlMsg msg=new HtmlMsg();
        msg.msgType=type;
        msg.htmlMsg=html;
        EventBus.getDefault().post(msg);

    }
    //播放
    public void player(String rtmpURL){
        // mIjkVideoView.setVideoPath("rtmp://123.57.149.112/hls/livestream201001");
        mIjkVideoView.setVideoPath(rtmpURL);
        mIjkVideoView.setHorizontalScrollBarEnabled(false);

    }
    //设置名字
    public void setInfo(String nickName){
        mTextViewName.setText(nickName);
    }
    //用户列表
    public void setUserList(int  userId){
        mUserList.add(userId);
        String userName = UsersManage.GetUserNickName(userId);
        mListUserName.add(userName);
        mSpinnerAdapter.notifyDataSetChanged();
        //发送用户
        UserManageInfo info=new UserManageInfo();
        info.nickName=userName;
        info.userId=userId;
        EventBus.getDefault().post(info);
    }

    private void setListener() {
        //设置触摸事件
        mIjkVideoView.setOnTouchListener(this);
        //准备监听
        mIjkVideoView.setOnPreparedListener(this);
        mSpinnerUser.setOnItemSelectedListener(this);
        mEditTextSend.setOnEditorActionListener(this);

    }

    private void initData() {
        mUserList.add(0);
        //调用Socket 登陆房间
        LoginRoom(900001, "123");
        mManager=getSupportFragmentManager();
        mFragments=new ArrayList<>();
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
        //获取屏幕高度和宽度
        DisplayMetrics metrics=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mHeightPixels = metrics.heightPixels;
        mWidthPixels = metrics.widthPixels;
        mSpinnerAdapter=new GiftBaseAdapter(this,mListUserName);
        mListUserName.add("所有人");
        mSpinnerUser.setAdapter(mSpinnerAdapter);
    }

    private void LoginRoom(int nRoomID, String sRoomPass){
        myApp = (MyApp) getApplication();
        mSocketUtil=new SocketUtil(myApp,this);
        userID = myApp.getLoginInfo().getUserslist().get(0).getUserID();
        String sUserPass = myApp.getLoginInfo().getUserslist().get(0).getUserPass();
        mSocketUtil.sendLogin(nRoomID+"",userID+"",sUserPass,sRoomPass);
    }

    private void setData() {

        //添加表情fragment
        FragmentTransaction transaction = mManager.beginTransaction();
        mFaceFragment = new FaceFragment();
        transaction.add(R.id.activity_live_fl_chat, mFaceFragment);
        mGiftFragment = new GiftFragment();
        transaction.add(R.id.activity_live_fl_chat, mGiftFragment);
        transaction.hide(mGiftFragment);
        transaction.commit();
        //声音
        audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
         volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
        //ijkplayer

        //添加fragment

        mFragments.add(new PublicChatFragment());
        mFragments.add(new PrivateChatFragment());
        mFragments.add(new ThemeFragment());
        mFragments.add(new TeaCherFragment());
        mPagerAdapterShow=new LiveActivityViewPager(getSupportFragmentManager(),this,mFragments);
        mViewPagerShow.setAdapter(mPagerAdapterShow);
        mTabLayoutShow.setupWithViewPager(mViewPagerShow);
    }
    private void initView() {
        mEditTextSend = (EditText) findViewById(R.id.activity_live_et_send);
        mSpinnerUser = (Spinner) findViewById(R.id.activity_live_sp_user);
        mButtonback = (Button) findViewById(R.id.activitY_live_bt_chat_back);
        mFrameLayoutFace = (FrameLayout) findViewById(R.id.activity_live_fl_chat);
        mIjkVideoView = (IjkVideoView) findViewById(R.id.activity_live_ijk);
        mLayoutTitle1 = (RelativeLayout) findViewById(R.id.activity_live_rl_title_1);
        mLayoutTitle2 = (RelativeLayout) findViewById(R.id.activity_live_rl_title_2);
        mTabLayoutShow = (TabLayout) findViewById(R.id.activity_live_tab_layout);
        mViewPagerShow = (ViewPager) findViewById(R.id.activity_live_view_pager);
        mRelativeLayoutIjk = (RelativeLayout) findViewById(R.id.activity_live_rl_ijk_player);
        mTextViewName = (TextView) findViewById(R.id.activity_live_tv_name);
        mImageViewAnimat = (ImageView) findViewById(R.id.activity_live_iv_animat);
        mViewPagerShow.setOffscreenPageLimit(3);
        //开启动画
        startAnimation();
    }

    private void startAnimation() {
        animationDrawable = (AnimationDrawable) mImageViewAnimat.getBackground();
        animationDrawable.start();
    }

    public void stopAnimation() {
        CountDownTimer timer=new CountDownTimer(1000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                animationDrawable.stop();
                mImageViewAnimat.setVisibility(View.GONE);
            }
        }.start();
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mLayoutTitle1.setVisibility(View.VISIBLE);
        mLayoutTitle2.setVisibility(View.VISIBLE);
        CountDownTimer timer=new CountDownTimer(5000,5000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }
            @Override
            public void onFinish() {
                mLayoutTitle1.setVisibility(View.GONE);
                mLayoutTitle2.setVisibility(View.GONE);
            }
        }.start();
        return true;

    }

    public void onClick(View view) {
        if (view != null) {
            switch (view.getId()){
                case R.id.activitY_live_bt_chat_back:
                    mFrameLayoutFace.setVisibility(View.GONE);
                    mButtonback.setVisibility(View.GONE);
                    break;
                //表情
                case R.id.activity_live_bt_face:
                    FragmentTransaction transaction = mManager.beginTransaction();
                    transaction.hide(mGiftFragment);
                    transaction.show(mFaceFragment);
                    transaction.commit();
                    mFrameLayoutFace.setVisibility(View.VISIBLE);
                    mButtonback.setVisibility(View.VISIBLE);
                    break;

                //礼物
                case R.id.activity_live_bt_gift:
                    FragmentTransaction transaction2 = mManager.beginTransaction();
                    transaction2.hide(mFaceFragment);
                    transaction2.show(mGiftFragment);
                    transaction2.commit();
                    mFrameLayoutFace.setVisibility(View.VISIBLE);
                    mButtonback.setVisibility(View.VISIBLE);

                    break;

                //横竖屏切换
                case R.id.activity_live_bt_cut:
                    if (getRequestedOrientation()== ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
                        ViewGroup.LayoutParams layoutParams=mIjkVideoView.getLayoutParams();
                        ViewGroup.LayoutParams layoutParams1 = mRelativeLayoutIjk.getLayoutParams();
                        layoutParams.height=444;
                        layoutParams.width=mWidthPixels;
                        layoutParams1.height=444;
                        layoutParams1.width=mWidthPixels;
                        mIjkVideoView.setLayoutParams(layoutParams);
                        mRelativeLayoutIjk.setLayoutParams(layoutParams1);
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }else {
                        ViewGroup.LayoutParams layoutParams= mIjkVideoView.getLayoutParams();
                        ViewGroup.LayoutParams layoutParams1 = mRelativeLayoutIjk.getLayoutParams();
                        layoutParams.width=mHeightPixels;
                        layoutParams.height=mWidthPixels;
                        layoutParams1.width=mHeightPixels;
                        layoutParams1.height=mWidthPixels;
                        mRelativeLayoutIjk.setLayoutParams(layoutParams1);
                        mIjkVideoView.setLayoutParams(layoutParams);
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    }
                    break;
                case R.id.activity_live_bt_jy:

                    //设置静音
                    if (is){
                        audio.setStreamVolume(AudioManager.STREAM_MUSIC,0,AudioManager.FLAG_PLAY_SOUND);
                        is=false;
                    }else {
                        audio.setStreamVolume(AudioManager.STREAM_MUSIC,volume,AudioManager.FLAG_PLAY_SOUND);
                        is=true;
                    }
                    break;
            }
        }
    }

    @Override
    public void onPrepared(IMediaPlayer mp) {
        mIjkVideoView.setVisibility(View.VISIBLE);
        mIjkVideoView.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSocketUtil.offSocket();
    }

    //用户列表监听
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        typeChat=2;
        if (mUserList!=null){
            receiverId = ((int) mUserList.get(position));
        }
        if (position==0){
            typeChat=2;
        }else{
            typeChat=1;
        }

    }




    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    //发送监听
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            String sSendMsg = mEditTextSend.getText().toString().trim();
            int MyUserID = myApp.getLoginInfo().getUserslist().get(0).getUserID();
            mSocketUtil.sendChatMsg("900001", MyUserID + "", typeChat, MyUserID, receiverId, sSendMsg);
            mEditTextSend.setText("");
            return true;
    }
}
